import { Injectable } from '@nestjs/common';
import * as npty from 'node-pty'
const os = require('os')
const pty = require('node-pty')

const termMap: Map<number, npty.IPty> = new Map()


@Injectable()
export class TerminalService {

  constructor() {
  }

  getTerminalPid(): string {
    const shell = os.platform() === "win32" ? "powershell.exe" : "bash";

    //绑定当前系统 node 环境
    const term = pty.spawn(shell, ["--login"], {
      name: "xterm",
      cols: 80,
      rows: 24,
      cwd: process.env.HOME,
      env: process.env,
      encoding: 'utf8'
    });
    termMap.set(term.pid, term)
    console.log('************', term.pid, termMap.keys())

    return term.pid.toString();
  }

  getTerminal(pid: string): npty.IPty {
    const term = termMap.get(Number(pid))
    return term
  }

  closeTerminal(pid: string) {
    termMap.delete(Number(pid))
  }
}
